package org.example.completed.controller;


import org.example.completed.domain.Review;
import org.example.completed.domain.User;
import org.example.completed.model.vo.ResultVO;
import org.example.completed.service.ReviewService;
import org.example.completed.service.UserService;
import org.example.completed.utils.BeanCopyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 评论表 ReviewController
 *
 * @since 2025-04-15
 */
@RestController
@RequestMapping("/review")
public class ReviewController {
    @Autowired
    private ReviewService reviewService;

    @Autowired
    private UserService userService;

    /**
     * 添加帖子评论
     * @param review 评论信息
     * @return 操作结果
     */
    @PostMapping("/add")
    public ResultVO<?> addReview(@RequestBody Review review) {
        User user = userService.getById(review.getUserId());
        Review review1 = BeanCopyUtil.copyObject(review, Review.class);
        review1.setUserAcoount(user.getUserAcoount());
        review1.setAvatarUrl(user.getImg());

        boolean success = reviewService.save(review1);
        return success ? ResultVO.ok("评论添加成功") : ResultVO.fail("评论添加失败");
    }

    /**
     * 根据帖子ID获取所有评论
     * @param postId 帖子ID
     * @return 评论列表
     */
    @GetMapping("/post/{postId}")
    public ResultVO<List<Review>> getReviewsByPostId(@PathVariable String postId) {
        List<Review> reviews = reviewService.lambdaQuery().eq(Review::getPostId, postId).list();
        return ResultVO.ok(reviews);
    }

    /**
     * 根据评论ID删除评论
     * @param id 评论ID
     * @return 操作结果
     */
    @PostMapping("/delete/{id}")
    public ResultVO<?> deleteReview(@PathVariable String id) {
        boolean success = reviewService.removeById(id);
        return success ? ResultVO.ok("评论删除成功") : ResultVO.fail("评论删除失败");
    }

    /**
     * 根据评论ID更新评论内容
     * @param id 评论ID
     * @param review 包含更新内容的评论对象
     * @return 操作结果
     */
    @PostMapping("/update/{id}")
    public ResultVO<?> updateReview(@PathVariable String id, @RequestBody Review review) {
        review.setId(id);
        boolean success = reviewService.updateById(review);
        return success ? ResultVO.ok("评论更新成功") : ResultVO.fail("评论更新失败");
    }
}

